using System;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Styling;
using Avalonia.Markup.Xaml;
using Avalonia.Markup.Xaml.Styling;
using AvaloniaUI.Modal.Controls;
using AvaloniaUI.Modal.Services;

namespace AvaloniaUI.Modal
{
    /// <summary>
    /// 提供用于注册和使用模态对话框的扩展方法
    /// </summary>
    public static class ModalExtensions
    {
        /// <summary>
        /// 向应用程序添加模态对话框支持
        /// </summary>
        /// <param name="app">Avalonia应用程序</param>
        /// <returns>应用程序实例</returns>
        public static T UseModal<T>(this T app) where T : Application
        {
            app.Styles.Add(new StyleInclude(new Uri("avares://AvaloniaUI.Modal/Styles"))
            {
                Source = new Uri("avares://AvaloniaUI.Modal/Styles/ModalStyles.axaml")
            });

            return app;
        }

        /// <summary>
        /// 获取模态对话框服务
        /// </summary>
        /// <param name="app">Avalonia应用程序</param>
        /// <returns>模态对话框服务</returns>
        public static IModalService GetModalService(this Application app)
        {
            return ModalService.Instance;
        }

        /// <summary>
        /// 异步显示模态对话框
        /// </summary>
        /// <typeparam name="TResult">结果类型</typeparam>
        /// <param name="app">Avalonia应用程序</param>
        /// <param name="content">对话框内容（通常是ViewModel）</param>
        /// <returns>对话框结果</returns>
        public static System.Threading.Tasks.Task<TResult?> ShowModalAsync<TResult>(this Application app, object content)
        {
            return app.GetModalService().ShowDialogAsync<TResult?>(content);
        }

        /// <summary>
        /// 异步显示模态对话框，并指定选项
        /// </summary>
        /// <typeparam name="TResult">结果类型</typeparam>
        /// <param name="app">Avalonia应用程序</param>
        /// <param name="content">对话框内容（通常是ViewModel）</param>
        /// <param name="options">对话框选项</param>
        /// <returns>对话框结果</returns>
        public static System.Threading.Tasks.Task<TResult> ShowModalAsync<TResult>(this Application app, object content, ModalDialogOptions options)
        {
            return app.GetModalService().ShowDialogAsync<TResult>(content, options);
        }

        /// <summary>
        /// 为窗口自动创建并添加ModalHost
        /// </summary>
        /// <param name="window">目标窗口</param>
        /// <returns>创建的ModalHost</returns>
        public static ModalHost EnsureModalHost(this Window window)
        {
            // 检查窗口中是否已有ModalHost
            var existingHost = FindModalHostInWindow(window);
            if (existingHost != null)
                return existingHost;
            
            // 创建新的ModalHost
            var host = new ModalHost { IsDefault = true };
            
            // 添加到窗口内容
            var rootPanel = window.Content as Panel;
            if (rootPanel == null)
            {
                // 如果窗口的内容不是Panel，则创建一个新的Grid
                var originalContent = window.Content;
                rootPanel = new Grid();
                window.Content = rootPanel;
                
                if (originalContent != null && originalContent is Control control)
                {
                    rootPanel.Children.Add(control);
                }
            }
            
            rootPanel.Children.Add(host);
            return host;
        }
        
        /// <summary>
        /// 在窗口中查找ModalHost
        /// </summary>
        /// <param name="window">要查找的窗口</param>
        /// <returns>找到的ModalHost，如果不存在则返回null</returns>
        private static ModalHost FindModalHostInWindow(Window window)
        {
            if (window == null)
                return null;
                
            // 如果窗口内容是Panel，查找其子元素
            if (window.Content is Panel panel)
            {
                foreach (var child in panel.Children)
                {
                    if (child is ModalHost host)
                        return host;
                }
            }
            
            return null;
        }
    }
}